<template>
    <el-container>
        <el-main class="wrapper">
            <section class="panel cms-content">
                <div class="panel-body">
                    <div class="cms-btn-group">
                        <el-button type="primary" icon="fa fa-refresh" @click="list()" size="small"> 刷新</el-button>
                        <el-button type="primary" icon="fa fa-plus" @click="create()" size="small"> 新增</el-button>
                        <el-button type="danger" icon="fa fa-trash" @click="multidel()" size="small"> 删除</el-button>
                    </div>
                    <div class="cms-search-group">
                        <div class="cms-search-item">
                            <el-input  size="medium" v-model="params.kwd" placeholder="请输入分类名称" class="input-with-select">
                                <el-button type="primary" @click="search()" slot="append" icon="el-icon-search"></el-button>
                            </el-input>
                        </div>
                    </div>
                    <el-table ref="multipleHandle"
                              v-loading="loading"
                              element-loading-text="努力加载中..."
                              element-loading-spinner="el-icon-loading"
                              @selection-change="handleSelectionChange"
                              tooltip-effect="dark" :data="listData.data"  border>
                        <el-table-column align="center" type="selection" width="50"></el-table-column>
                        <el-table-column align="center" prop="id" label="编号" width="60"></el-table-column>
                        <el-table-column align="center" prop="thumb" label="头像" width="120">
                            <template slot-scope="scope">
                                <img :src="scope.row.thumb" style="height: 45px;width: 45px;border-radius: 50%"/>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="名称" width="150"></el-table-column>
                        <el-table-column align="center" prop="type" label="所属" width="75">
                            <template slot-scope="scope">
                                <el-tag v-if="scope.row.type == 1" type="primary" size="small">美文</el-tag>
                                <el-tag v-if="scope.row.type == 2" type="primary" size="small">视频</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="created_at" label="创建时间" width="200"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" @click="edit(scope.row)" icon="fa fa-edit" plain>
                                    编辑</el-button>
                                <el-button icon="fa fa-trash" @click="destroy(scope.row.id)" type="danger" size="mini" plain> 删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination :pageData="listData" :params="params" @list="list"/>
                </div>
            </section>
        </el-main>
        <!-- 表单弹窗 @open="resetForm('form')"-->
        <el-dialog
                v-if="dialog.show"
                :title="dialog.title"
                custom-class="cms-dialog"
                :top="dialog.top"
                :visible.sync="dialog.show"
                :width="dialog.width">
            <el-form :model="form" ref="form" label-width="80px">
                <el-form-item required label="头像：" prop="thumb" :rules="[{ required: true, message: '请上传分类头像', trigger: 'change'}]">
                    <el-upload
                            class="avatar-uploader"
                            :action="upload"
                            :show-file-list="false"
                            :headers="myHeaders"
                            :on-success="uploadSuccess"
                            :before-upload="beforeUpload" name="image">
                        <img v-if="form.thumb" :src="form.thumb" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item required label="名称：" prop="name" :rules="[{ required: true, message: '请填写分类名称', trigger: 'blur'}]">
                    <el-input v-model="form.name" placeholder="请填写分类名称"></el-input>
                </el-form-item>
                <el-form-item required label="所属：" prop="type">
                    <el-radio-group v-model="form.type">
                        <el-radio border :label="1">美文</el-radio>
                        <el-radio border :label="2">视频</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialog.show = false">取 消</el-button>
                <el-button type="primary" @click="update('form')">确 定</el-button>
              </span>
        </el-dialog>
    </el-container>
</template>

<script>
    import {mapGetters} from 'vuex';
    import {CategoryList,CategoryUpdate,CategoryDestroy} from '@/utils/request';
    import Pagination from '@/components/pagination';
    export default {
        components: {Pagination},
        data() {
            return {
                listData: [],//列表数据
                multipleSelection:[],//多选项
                params: {page:1,kwd:''},
                dialog: {
                    title: '',
                    top: '15vh',
                    show: false,
                    width: '550px'
                },
                form: null,
            }
        },
        activated(){
            this.list();
            this.multipleSelection = [];
        },
        computed: {
            ...mapGetters(['loading','upload']),
            myHeaders() {
                return {'Authorization': 'Bearer ' + this.$storage.get('token'), 'Accept': 'application/json'}
            },
        },
        methods: {
            //回调1
            uploadSuccess(res) {
                if (res.code) {
                    this.$message.error(res.msg);
                } else {
                    this.form.thumb = res.data;
                }
            },
            //回调2
            beforeUpload(file) {
                const imgType = ['image/png','image/jpeg'];
                const isSize= file.size / 1024 / 1024 < 0.1;
                if (!imgType.includes(file.type)) {
                    this.$message.error('上传头像图片只能是 JPG,JPEG,PNG 格式!');return false;
                }
                if (!isSize) {
                    this.$message.error('上传头像图片大小不能超过 100Kb!');return false;
                }
                return true;
            },
            // 新增
            create(){
                this.form = {
                    id:0,
                    name:'',
                    type:1,
                    thumb:'',
                };
                this.dialog.title = '新增分类';
                this.dialog.show = true;
            },
            // 编辑
            edit(info){
                this.form = {
                    id: info.id,
                    type:info.type,
                    name: info.name,
                    thumb: info.thumb,
                };
                this.dialog.title = '编辑分类';
                this.dialog.show = true;
            },
            // 多选删除
            multidel(){
                if(this.multipleSelection.length == 0){
                    this.$message.error('请至少选择一项你要删除的项');return false;
                }
                this.destroy(this.multipleSelection);
            },
            //删除
            destroy(id){
                let msg;
                if(id.length){
                    msg = '确定要删除选中的分类信息吗？';
                }else{
                    msg = '确定要删除该分类信息吗？';
                }
                this.$confirm(msg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    customClass: 'cms-message-box',
                    type: 'warning'
                }).then(() => {
                    CategoryDestroy({id: id}).then((res) => {
                        if (res.code) {
                            this.$message.error(res.msg);
                        } else {
                            this.list();
                        }
                    });
                }).catch(() => {});
            },
            // 筛选
            search(){
                this.params.page = 1;
                this.list();
            },
            // 列表
            list(){
                this.$store.dispatch('setLoading', true);
                CategoryList({params: this.params}).then((res)=>{
                    if (res.code) {
                        this.$message.error(res.msg);
                    } else {
                        this.listData = res.data;
                    }
                    this.$store.dispatch('setLoading', false);
                })
            },
            // 更新
            update(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        CategoryUpdate(this.form).then((res)=>{
                            if(res.code){
                                this.$message.error(res.msg);
                            }else{
                                this.$message({
                                    type: 'success',
                                    duration: '1000',
                                    message: res.msg,
                                    onClose:() =>{
                                        this.dialog.show = false;
                                        this.list();
                                    }
                                });
                            }
                        });
                    }
                });
            },
            handleSelectionChange(val) {
                let select = [];
                if(val.length > 0){
                    val.filter((item)=>{
                        if(select.indexOf(item.id) === -1){
                            select.push(item.id)
                        }
                    });
                    this.multipleSelection = select;
                }else{
                    this.multipleSelection = [];
                }
            }
        }
    }
</script>
